package com.csg.boot.starter.builder;

import com.csg.boot.starter.constant.SwaggerProperties;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.service.AuthorizationScope;
import springfox.documentation.service.SecurityReference;
import springfox.documentation.spi.service.contexts.SecurityContext;

import java.util.Collections;
import java.util.List;

/**
 * @author george
 */
public class SecurityContextBuilder implements BaseBuilder<SecurityContext, SwaggerProperties.SecurityProperties> {

    private static SecurityContextBuilder builder = new SecurityContextBuilder();

    private static AuthorizationScopeBuilder authorizationScopeBuilder = AuthorizationScopeBuilder.getInstance();

    private SecurityContextBuilder() {
    }

    public static SecurityContextBuilder getInstance() {
        return builder;
    }

    @Override
    public SecurityContext build(SwaggerProperties.SecurityProperties properties) {
        return SecurityContext.builder()
                .securityReferences(securityReferences(properties))
                .forPaths(PathSelectors.regex(properties.getPathRegex()))
                .build();
    }

    private List<SecurityReference> securityReferences(SwaggerProperties.SecurityProperties properties) {
        SecurityReference securityReference = SecurityReference.builder()
                .reference(properties.getName())
                .scopes(scopes(properties.getScopes()))
                .build();
        return Collections.singletonList(securityReference);
    }

    private AuthorizationScope[] scopes(List<SwaggerProperties.AuthorizationScopeProperties> scopes) {
        List<AuthorizationScope> authorizationScopes = authorizationScopeBuilder.build(scopes);
        return authorizationScopes.toArray(new AuthorizationScope[authorizationScopes.size()]);
    }
}
